<?php

/**
 * OpenID represents the data needed to identity a user through Open ID framework.
 * This class will auth the user with different provider using the Janrain openid php library,
 * and returning the standard username, ID.
 */
Yii::import('application.vendors.Auth.OpenID.Consumer', true);
Yii::import('application.vendors.Auth.OpenID.FileStore', true);
Yii::import('application.vendors.Auth.OpenID.google_discovery', true);
Yii::import('application.vendors.Auth.OpenID.SReg', true);
Yii::import('application.vendors.Auth.OpenID.PAPE', true);
Yii::import('application.vendors.Auth.OpenID.AX', true);

class OpenIDIndentity extends CBaseUserIdentity implements IUserIdentity {

    public $consumer;
    public $loginUrl = 'openid';
    public $returnUrl = array('openid/return');
    public $store = '';
    public $provider;
    public $name;
    public $id;
    public $timestamp = 259200;  // 3 days

    public function __construct($provider) {
    	if($this->store == '' || $this->store == null)
    	    $this->store = $_SERVER['DOCUMENT_ROOT']."/tmp/_php_openid";
        if (!file_exists($this->store) && !mkdir($this->store))
            return false;
        Yii::app()->session->open();
        $this->provider = $provider;
        $store = new Auth_OpenID_FileStore($this->store);
        $this->consumer = new Auth_OpenID_Consumer($store);
        if (Yii::app()->user->getState('googleapp') != null)
            new GApps_OpenID_Discovery($this->consumer);
    }

    private function makeURL($URL) {
        $scheme = 'http';
        if (isset($_SERVER['HTTPS']) and $_SERVER['HTTPS'] == 'on') {
            $scheme .= 's';
        }
        return $scheme . '://' . $_SERVER['SERVER_NAME'] . $URL;
    }

    public function authenticate() {
        $request = $this->consumer->begin($this->provider);
        if (!$request)
            return false;
        Yii::app()->session->add('domain',$this->provider);
        
        //AX extensions
        $attribute[] = Auth_OpenID_AX_AttrInfo::make('http://axschema.org/contact/email', 2, 1, 'email');
        $attribute[] = Auth_OpenID_AX_AttrInfo::make('http://axschema.org/namePerson/first', 1, 1, 'firstname');
        $attribute[] = Auth_OpenID_AX_AttrInfo::make('http://axschema.org/namePerson/last', 1, 1, 'lastname');

        $ax = new Auth_OpenID_AX_FetchRequest;

        //PAPE extensions
        //$pape = new Auth_OpenID_PAPE_Request(null,0); <<< Force relogin.

        $pape = new Auth_OpenID_PAPE_Request(null);
        
        if ($pape)
            $request->addExtension($pape);
        foreach ($attribute as $attr) {
            $ax->add($attr);
        }
        if ($ax)
            $request->addExtension($ax);
        if (!$request->shouldSendRedirect())
            $redirect_url = $request->redirectURL($this->makeURL('/index.php/' . $this->loginUrl), $this->makeURL(CHtml::normalizeUrl($this->returnUrl)));
        else
            return false;

        if (Auth_OpenID::isFailure($redirect_url)) {
            return false;
        } else {
            return $redirect_url;
        }
    }

    public function checkAutheticate() {
        $response = $this->consumer->complete($this->makeURL(CHtml::normalizeUrl($this->returnUrl)));
        if ($response->status == Auth_OpenID_CANCEL || $response->status == Auth_OpenID_FAILURE) {
            return false;
        }
        $openid = $response->getDisplayIdentifier();
        $this->id = htmlentities($openid);

        $ax = new Auth_OpenID_AX_FetchResponse;
        $data = $ax->fromSuccessResponse($response)->data;
        $this->name = $this->id;
        if (isset($data['http://axschema.org/namePerson/first'][0]))
            $this->name = $data['http://axschema.org/namePerson/first'][0];
        if (isset($data['http://axschema.org/namePerson/last'][0]))
            $this->name = trim($this->name . " " . $data['http://axschema.org/namePerson/last'][0]);
        Yii::app()->session->add('email',$data['http://axschema.org/contact/email'][0]);
        Yii::app()->session->add('name',$this->name);
        Yii::app()->user->login($this);
        return true;
    }
    
    public function getId() {
        return $this->id;
    }

    public function getIsAuthenticated() {
        if (!$this->IsAuthenticated)
            die('check');
        return $this->IsAuthenticated;
    }

    public function getName() {
        return $this->name;
    }

    public function getPersistentStates() {
        return parent::getPersistentStates();
    }

}

?>